package com.liveneo.stoat.sys.web;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributesModelMap;

import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.liveneo.stoat.common.page.PageParam;
import com.liveneo.stoat.common.util.MD5;
import com.liveneo.stoat.common.web.BaseController;
import com.liveneo.stoat.sys.entity.PrpmUser;
import com.liveneo.stoat.sys.service.UserService;
/**
 * 
 *@Description: 用户管理
 *@Author:hjt 
 *@Since:2017年1月13日 下午9:47:45 
 *@Version:1.0.0
 */
@Controller
@RequestMapping ("/sys/user")
public class UserController extends BaseController{
	private static String BASE_PATH = "sys/user";
	@Resource
	private UserService userService;

	/**  用户列表   */
	@RequestMapping (value = "/list")
	public String list(PrpmUser prpmUser, ModelMap modelMap, PageParam pageParam){
		logger.info("UserController.list start");
		try {
			PageInfo<PrpmUser> pageInfo = userService.queryListWithPage(prpmUser, pageParam);
			modelMap.put("pageInfo", pageInfo);
			modelMap.put("prpmUser", prpmUser);
		} catch (Exception e) {
			logger.info("UserController.list error>>>"+e.getMessage());
		}
		logger.info("UserController.list end");
		return BASE_PATH + "/userList";
	}
	
	/**  跳转添加/修改用户   */
	@RequestMapping (value = "/toAdd")
	public String toAdd(PrpmUser prpmUser, ModelMap modelMap){
		try {
			if(StringUtils.isNotBlank(prpmUser.getId())){
				prpmUser = userService.selectById(prpmUser.getId());
			}
		} catch (Exception e) {
			
		}
		modelMap.put("prpmUser", prpmUser);
		return BASE_PATH + "/userAdd";
	}
	
	/**
	 * 添加修改用户
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/save")
	public String save(PrpmUser user, BindingResult br, RedirectAttributesModelMap modelMap, String oldLoginName) {
		logger.info("UserController.save start");
		if (br.hasErrors()) {
            return toAdd(user, modelMap);
        }
		
        //检验登录名是否存在
        if (!"true".equals(checkLoginName(oldLoginName, user.getLoginName()))) {
        	putErrorMsg(modelMap, "登录名已存在，请更换!");
            return toAdd(user, modelMap);
        }
		try {
			if(StringUtils.isBlank(user.getPassword())){
				user.setPassword(MD5.GetMD5Code("111111"));
			}
			boolean flag = userService.save(user);
			if(flag) {
				putSuccessMsg(modelMap, "保存用户信息成功");
			} else {
				putErrorMsg(modelMap, "保存用户信息失败");
			}
		} catch (Exception e) {
			putErrorMsg(modelMap, "保存用户信息异常");
			logger.error("UserController.save error>>" + e.getMessage());
		}
		logger.info("UserController.save end");
		return redirect("redirect:/{}/list", BASE_PATH);
	}
	
	/**
	 * 删除用户
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/del/{id}")
	public String del(@PathVariable String id, RedirectAttributesModelMap modelMap) {
		logger.info("UserController.del start");
		try {
			boolean flag = userService.deleteById(id);
			if(flag){
				putSuccessMsg(modelMap, "删除用户成功");
			} else {
				putErrorMsg(modelMap, "删除用户失败");
			}
		} catch (Exception e) {
			putErrorMsg(modelMap, "删除用户异常");
			logger.error("UserController.del error>>" + e.getMessage());
		}
		logger.info("UserController.del end");
		return redirect("redirect:/{}/list", BASE_PATH);
	}
	
	/**
	 * 批量删除用户
	 * @param user
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/datadel")
	public String datadel(RedirectAttributesModelMap modelMap) {
		logger.info("UserController.datadel start");
		String res = "-1";
		try {
			List<String> idList = Lists.newArrayList();
			String[] ids = getStrings("ids");
			if(ids != null){
				for(String id : ids){
					idList.add(id);
				}
			}
			boolean flag = false;
			if(idList.size() > 0){
				flag = userService.deleteByIds(idList);
			}
			if(flag){
				res = "1";
			}
//			boolean flag = userService.deleteByIds("");
//			if(flag){
//				putSuccessMsg(modelMap, "批量删除用户成功");
//			} else {
//				putErrorMsg(modelMap, "批量删除用户失败");
//			}
		} catch (Exception e) {
			putErrorMsg(modelMap, "批量删除用户异常");
			logger.error("UserController.datadel error>>" + e.getMessage());
		}
		logger.info("UserController.datadel end");
		//return redirect("redirect:/{}/list", BASE_PATH);
		return res;
	}
	
	/**  校验重复登录名   */
	@ResponseBody
    @RequestMapping (value = "/checkLoginName")
    public String checkLoginName (String oldLoginName, String loginName) {
		logger.info("UserController.checkLoginName   start");
		try {
			//如果没有修改loginName
		    if (loginName != null && StringUtils.equals(loginName, oldLoginName)) {
		        return "true";
		    } else if (loginName != null && userService.findByLoginName(loginName) == null) {
		        return "true";
		    }
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("UserController.checkLoginName   error-->"+e.getMessage());
			return "false";
		}
		logger.info("UserController.checkLoginName   end");
		return "false";
    }
	
	
}
